/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fourbox;

/**
 *
 * @author hartono
 */
public class ServerProtocol {
   
    public static final int CONNECTION_DEAD = -1;
    public static final int CONNECTION_ALIVE = 1;
    
    public static final int LOGIN_SUCCESS = 2;
    public static final int LOGIN_FAILED = 3;
    
    public static final int LOGOUT_SUCCESS = 4;
    
    public String username = null;
    public static final int RECEIVE_UPDATE_FROM_CLIENT = 5; // respon kalo si file pada client ada yang berubah, lagi online    
    public static final int RECEIVE_REGULAR_UPDATE_FROM_CLIENT = 6; 

    private ServerProtocol(String username) {
        this.username = username;

    }

    public static ServerProtocol serverAuthenticate(byte[] message) {
        ServerProtocol retval = null;

        // debug
        System.out.println("Protocol : Autenticate");
        System.out.println("Protocol : message = " + FUtil.byteArrayToString(message));

        if (message.length >= 1) {
            // get message id
            byte messageID = message[0];            
            // melakukan pemrosesan
            if (messageID == ProtocolMessage.CLIENT_MSG_LOGIN) {
                System.out.println("Protocol : message name = CLIENT MSG LOGIN");
                // login, username data
                int uLength = (int) message[1];
                int pLength = (int) message[2];

                char[] uString = new char[uLength];
                char[] pString = new char[pLength];

                for (int i = 0; i < uLength; i++) {
                    uString[i] = (char) message[3 + i];
                }
                for (int i = 0; i < pLength; i++) {
                    pString[i] = (char) message[23 + i];
                }
                String username = String.valueOf(uString);
                String password = String.valueOf(pString);
                System.out.println("Protocol : checking username and password : " + username + "," + password);
                if (DBHelper.login(username, password)) {
                    retval = new ServerProtocol(username);
                }
            }
        } 
        return retval;
    }

    public int processMessage(byte[] message) {
        byte messageID = message[0];
        if (messageID == ProtocolMessage.CLIENT_MSG_LOGOUT) { // LOGOUT                            
            return CONNECTION_DEAD;
        } else if (messageID == ProtocolMessage.CLIENT_MSG_KEEP_ALIVE) {
            return CONNECTION_ALIVE;
        } else if (messageID == ProtocolMessage.CLIENT_MSG_LIST_FILES_CHANGES){
            return RECEIVE_UPDATE_FROM_CLIENT;
        } else if (messageID == ProtocolMessage.CLIENT_MSG_LIST_FILES_REGULAR){
            return RECEIVE_REGULAR_UPDATE_FROM_CLIENT;
        }

        return CONNECTION_ALIVE;        
    }
}
